<?php
/**
 * Created by PhpStorm.
 * User: jiangjun
 * Date: 2017/4/24
 * Time: 11:47
 */

namespace HuoService\Finance\Logic;


use HuoCore\Logic\BaseLogic;
use HuoService\Finance\Model\FundOrderModel;
use Illuminate\Support\Facades\DB;

class FundLogic extends BaseLogic
{

    /**
     * 获取提现订单的信息
     * @param $orderid
     * @return array
     */
    public static function fund($orderid){
        $fund = FundOrderModel::where("orderid",$orderid)->first();
        if($fund){
            return self::outData($fund->toArray());
        }else{
            return self::outError("提现订单不存在");
        }
    }


    /**
     * 提现订单支付
     * @param $orderid
     * @return mixed
     */
    public static function pay($orderid){
        $fund = self::fund($orderid);
        if(!empty($fund['errorCode'])){
            return self::outData($fund);
        }
        $checkResult = self::checkFundValid($fund);
        if($checkResult['errorCode']){
            return self::outData($checkResult);
        }

        switch($fund['paytype']){
            case 1:
                $alipayResult = self::doAlipay($fund);
                if($alipayResult['errorCode']){
                    return self::outError($alipayResult['errorDescription']);
                }
                break;
        }
        return self::outSuccess($alipayResult['result']);
    }


    /**
     * 支付宝转账支付
     * @param array $fund
     * @return mixed
     */
    private static function doAlipay($fund=array()){
        $financeConn = DB::connection('mysql_finance');
        $financeConn->beginTransaction();

        $fund['paydata'] = json_decode($fund['paydata'],true);
        $payResult = AlipayLogic::transfer([
            "out_biz_no"    =>  $fund['orderid'],
            "payee_type"    =>  $fund['paydata']['payee_type'],
            "payee_account"    =>  $fund['receive_account'],
            "amount"    =>  $fund['amount'] - $fund['fee'],
            "payer_show_name"    =>  $fund['paydata']['payer_show_name'],
            "payee_real_name"    =>  $fund['paydata']['payee_real_name'],
            "remark"    =>  $fund['paydata']['remark'],
        ]);
        if(empty($payResult['errorCode'])){
            //  处理成功
            //  先更改提现订单状态为已支付
            FundOrderModel::where("orderid",$fund['orderid'])->update(['status'=>1,"paytime"=>date("Y-m-d H:i:s")]);
            $financeConn->commit();
            return self::outSuccess($payResult['result']);
        }else{
            //  处理失败
            //  更新状态为处理失败
            $updateFailResult = FundOrderModel::where("orderid",$fund['orderid'])->update(['status'=>2,"error_reason"=>$payResult['errorDescription']]);
            if(!$updateFailResult){
                $financeConn->rollback();
                return self::outError($payResult['errorDescription']);
            }

            //失败后返回提现金额
            $huoConn = DB::connection('mysql_hx');

//            根据提现类型是档口还是普通用户，不同处理。。。。后期需要统一
            if(empty($fund['sellerid'])){
                $billResult = BillLogic::addBillIn([
                    "userid"    =>  $fund['userid'],
                    "money"     =>  $fund['amount'] + $fund['fee'],
                    "money_type"    =>  BillLogic::MONEY_HTCZ,
                    "deal_flow"     =>  $fund['orderid'],
                    "name"          =>  "用户提现失败",
                    "intro"          =>  "用户提现失败",
                ]);
                if($billResult['errorCode']){
                    $huoConn->rollback();
                    $financeConn->rollback();
                    return self::outError($billResult['errorDescription']);
                }
            }else{
                $billResult = SellerBillLogic::addBillIn([
                    "sellerid"    =>  $fund['sellerid'],
                    "money"     =>  $fund['amount'] + $fund['fee'],
                    "money_type"    =>  SellerBillLogic::MONEY_CZ,
                    "deal_flow"     =>  $fund['orderid'],
                    "name"          =>  "用户提现失败",
                    "intro"          =>  "用户提现失败",
                ]);
                if($billResult['errorCode']){
                    $huoConn->rollback();
                    $financeConn->rollback();
                    return self::outError($billResult['errorDescription']);
                }
            }

            $huoConn->commit();
            $financeConn->commit();
            return self::outError($payResult['errorDescription']);
        }
    }

    private static function makeFundError(){

    }

    private static function makeFundSuccess(){

    }


    /**
     * 检查提现订单状态是否可支付
     * @param array $fund
     * @return array
     */
    private static function checkFundValid($fund=array()){
        switch($fund['status']){
            case 1:
                return self::outError("该提现订单已经支付过了");
                break;
            case 2:
                return self::outError("该提现订单处理失败，请重新申请提现");
                break;
            case 3:
                return self::outError("该提现订单审核不通过，请重新申请提现");
                break;
            default:
                return self::outSuccess(1);
            break;
        }
    }

    /**
     * 提现申请流程
     * @param array $data
     * @return array|mixed
     */
    public static function create($data=array()){
        $realData = self::organizeParam($data);
        if(!empty($realData['errorCode'])){
            return $realData;
        }
        $realData['orderid'] = self::generateOrderid();


        $huoConn = DB::connection('mysql_hx');
        $financeConn = DB::connection('mysql_finance');
        $huoConn->beginTransaction();
        $financeConn->beginTransaction();

        $fundOrderModel = new FundOrderModel();

//        先保存提现订单
        $order = $fundOrderModel->create($realData);
        if(!$order->id){
            $huoConn->rollback();
            $financeConn->rollback();
            return self::outError("系统出错，提现订单无法生成");
        }

//        生成账单
        if(empty($realData['sellerid'])){
            $billResult = BillLogic::addBillOut([
                "userid"    =>  $realData['userid'],
                "money"     =>  $realData['amount'] + $realData['fee'],
                "money_type"    =>  BillLogic::MONEY_TX,
                "deal_flow"     =>  $realData['orderid'],
                "name"          =>  "用户提现",
                "intro"          =>  "提现",
            ]);
            if($billResult['errorCode']){
                $huoConn->rollback();
                $financeConn->rollback();
                return self::outError($billResult['errorDescription']);
            }
        }else{
            $billResult = SellerBillLogic::addBillOut([
                "sellerid"    =>  $realData['sellerid'],
                "money"     =>  $realData['amount'] + $realData['fee'],
                "money_type"    =>  SellerBillLogic::MONEY_TX,
                "deal_flow"     =>  $realData['orderid'],
                "name"          =>  "用户提现",
                "intro"          =>  "提现",
            ]);
            if($billResult['errorCode']){
                $huoConn->rollback();
                $financeConn->rollback();
                return self::outError($billResult['errorDescription']);
            }
        }

        $huoConn->commit();
        $financeConn->commit();
        return self::outSuccess(["orderid"=>$realData['orderid']]);
    }


    /** 参数检查，并返回同意的数据格式
     * @param $data
     * @return mixed
     */
    private static function organizeParam($data){
        switch($data['paytype']){
            case 1:
                if(empty($data['payee_account'])){
                    return self::outError("请填写支付宝收款方账户");
                }
                if(empty($data['amount']) || !is_numeric($data['amount'])){
                    return self::outError("请输入提现金额");
                }
                if($data['amount'] < 0){
                    return self::outError("提现金额错误，必须大于0");
                }
                if(empty($data['payee_real_name'])){
                    return self::outError("请填写支付宝收款方真实姓名");
                }
                if(empty($data['userid'])){
                    return self::outError("参数错误");
                }
                $realData = [
                    "userid"=>$data['userid'],
                    "amount"=>$data['amount'],
                    "paytype"=>$data['paytype'],
                    "paydata"=>json_encode([
                        "payee_type"    =>  "ALIPAY_LOGONID",
                        "payer_show_name"    =>  "一起火",
                        "payee_real_name"    =>  $data['payee_real_name'],
                        "remark"    =>  "一起火账户提现".$data['amount']."元",
                    ]),
                    "fee"=>0,
                    "receive_account"   =>  $data['payee_account'],
                ];

                //查看是不是档口提现
                $seller = SellerLogic::uSeller($data['userid']);
                if(!empty($seller['errorCode'])){
                    $realData['sellerid'] = 0 ;
                }else{
                    $realData['sellerid'] = $seller['id'];
                }
                return self::outData($realData);
                break;
        }
    }


    /** 生成唯一的提现订单id
     * @return string
     */
    private static function generateOrderid(){
        $id = date('YmdHis', time()) . str_pad(rand('1', '99999'), 5, '0', STR_PAD_LEFT);
        $order = FundOrderModel::where("orderid",$id)->first();
        if ( empty($order) )
        {
            return $id;
        }
        else
        {
            return self::generateOrderid();
        }
    }
}